package com.my.zl.common.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Locale;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

public class FreemarkerTool {
    private static final Logger LOGGER = LoggerFactory.getLogger(FreemarkerTool.class);
    
    private static Configuration CFG = new Configuration(Configuration.VERSION_2_3_30);

    static {
        CFG.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_30));
    }

    // 加载模板目录，绝对文件路径
    public static void initFreemarker(String dir) {
        try {
            CFG.setDirectoryForTemplateLoading(new File(dir)); 
            CFG.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
            CFG.setEncoding(Locale.getDefault(), "UTF-8");
            CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            CFG.setLocale(Locale.CHINA);
        } catch (Exception e) {
            LOGGER.error("模板加载异常>>{}", e);
        }
    }
    // 加载模板目录，项目内部文件路径
    public static void initFreemarker2(String dir) {
        try {
            CFG.setClassForTemplateLoading(FreemarkerTool.class, dir);
            CFG.setTagSyntax(Configuration.SQUARE_BRACKET_TAG_SYNTAX);
            CFG.setEncoding(Locale.getDefault(), "UTF-8");
            CFG.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            CFG.setLocale(Locale.CHINA);
        } catch (Exception e) {
            LOGGER.error("模板加载异常>>{}", e);
        }
    }
    /** 生成文件*/
    public static void processFile(Object rootMap, String enc, String templateName, String outputName) {
        Writer out = null;
        try {
            Template tpl = CFG.getTemplate(templateName, enc);
            File tf = new File(outputName);
            File pf = tf.getParentFile();
            pf.mkdirs();
            out = new OutputStreamWriter(new FileOutputStream(tf), enc);
            tpl.process(rootMap, out);
            out.flush();
        } catch (Exception e) {
            LOGGER.error("文件生成异常>>{}", e);
        } finally {
            IOUtils.closeQuietly(out);
        }
    }
    
    /**
     * 生成 String
     */
    public static String processString(Object params,String templateName, String enc) {
        try {
            Template template = CFG.getTemplate(templateName, enc);
            StringWriter result = new StringWriter();
            template.process(params, result);
            return result.toString();
        } catch (Exception e) {
            LOGGER.error("文件生成异常>>{}", e);
        }
        return null;
    }

}
